<template>
  <div>
    <div>
      <h2>面试回答智能分析测试</h2>
      <div class="page-main">
        <div>
          <textarea v-model="inputText" placeholder="请输入面试回答内容" style="width: 600px;height: 100px"></textarea>
        </div>
        <div class="button-group">
          <button class="audio-ctrl-btn" :class="advantageStatus" @click="analyzeAdvantages">
            {{ advantageButtonText }}
          </button>
          <button class="audio-ctrl-btn" :class="disadvantageStatus" @click="analyzeDisadvantages">
            {{ disadvantageButtonText }}
          </button>
        </div>
        <br>
        <div>
          <h3 style="color: green;">优点分析</h3>
          <div v-html="formattedAdvantageText" class="result-container advantage"></div>
        </div>
        <div>
          <h3 style="color: red;">缺点分析</h3>
          <div v-html="formattedDisadvantageText" class="result-container disadvantage"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { downloadPCM, downloadWAV } from '../../js/download';
import CryptoJS from 'crypto-js';
import VConsole from 'vconsole';
import { Base64 } from 'js-base64';

export default {
  name: 'SparkModel',
  data() {
    return {
      inputText: '在工具链上，我习惯使用 Maven 进行依赖管理，通过 Git 进行版本控制，持续集成方面熟悉 Jenkins 流水线配置，容器化部署采用 Docker+Kubernetes 组合，曾主导将单体应用重构为容器化微服务集群，资源利用率提升 40%。',
      advantageText: '',
      disadvantageText: '',
      formattedAdvantageText: '',
      formattedDisadvantageText: '',
      advantageStatus: 'init',
      disadvantageStatus: 'init',
      totalRes: '',
      httpUrl: new URL("https://spark-api.xf-yun.com/v3.5/chat"),
      modelDomain: '',
      ttsWS: null,
      appId: 'e9f15e7b',
      apiSecret: 'YTk4MzhhOGY5MDNjNWI2ZjAzYjEwMWVi',
      apiKey: '8f4950aa42fdca8eac189b3edb74da82',
      buttonStates: {
        init: '查询',
        loading: '分析中...',
        error: '重试'
      }
    };
  },
  computed: {
    advantageButtonText() {
      return this.buttonStates[this.advantageStatus] || '查询优点';
    },
    disadvantageButtonText() {
      return this.buttonStates[this.disadvantageStatus] || '查询缺点';
    }
  },
  created() {
    if (process.env.NODE_ENV === 'development') {
      new VConsole();
    }
    this.getModelDomain();
  },
  methods: {
    getModelDomain() {
      switch (this.httpUrl.pathname) {
        case "/v1.1/chat":
          this.modelDomain = "lite";
          break;
        case "/v2.1/chat":
          this.modelDomain = "generalv2";
          break;
        case "/v3.1/chat":
          this.modelDomain = "generalv3";
          break;
        case "/v3.5/chat":
          this.modelDomain = "generalv3.5";
          break;
        default:
          this.modelDomain = "generalv3.5";
      }
    },

    getWebsocketUrl(questionType) {
      return new Promise((resolve, reject) => {
        try {
          const host = window.location.host;
          const date = new Date().toGMTString();
          const algorithm = 'hmac-sha256';
          const headers = 'host date request-line';
          const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${this.httpUrl.pathname} HTTP/1.1`;
          const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.apiSecret);
          const signature = CryptoJS.enc.Base64.stringify(signatureSha);
          const authorizationOrigin = `api_key="${this.apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
          const authorization = btoa(authorizationOrigin);
          const url = `wss://${this.httpUrl.host}${this.httpUrl.pathname}?authorization=${authorization}&date=${date}&host=${host}`;
          resolve(url);
        } catch (error) {
          reject(error);
        }
      });
    },

    connectWebSocket(questionType) {
      if (questionType === 'advantage') {
        this.advantageStatus = 'loading';
      } else {
        this.disadvantageStatus = 'loading';
      }

      this.getWebsocketUrl().then(url => {
        if ('WebSocket' in window) {
          this.ttsWS = new WebSocket(url);
        } else {
          alert('浏览器不支持WebSocket');
          this.setStatus(questionType, 'error');
          return;
        }

        this.ttsWS.onopen = () => {
          this.webSocketSend(questionType);
        };

        this.ttsWS.onmessage = e => {
          this.handleResult(e.data, questionType);
        };

        this.ttsWS.onerror = e => {
          console.error('WebSocket错误:', e);
          this.setStatus(questionType, 'error');
          alert('WebSocket连接错误，请检查控制台日志');
        };

        this.ttsWS.onclose = e => {
          console.log('WebSocket关闭:', e);
          this.setStatus(questionType, 'init');
        };
      }).catch(error => {
        console.error('获取WebSocket URL失败:', error);
        this.setStatus(questionType, 'error');
      });
    },

    webSocketSend(questionType) {
      let queryPrompt = '';
      if (questionType === 'advantage') {
        queryPrompt = `${this.inputText} 请仅分析这段回答的优点，要求以有序列表返回所有优点，每行一个优点，使用**包裹关键点，不需要返回缺点。`;
      } else {
        queryPrompt = `${this.inputText} 请仅分析这段回答的缺点，并给出改进建议，要求以有序列表返回所有内容，每行一个条目，使用**包裹关键点，不需要返回优点。`;
      }

      const params = {
        "header": {
          "app_id": this.appId, "uid": "fd3f47e4-d"
        },
        "parameter": {
          "chat": {
            "domain": this.modelDomain, "temperature": 0.5, "max_tokens": 2048
          }
        },
        "payload": {
          "message": {
            "text": [
              { "role": "user", "content": "中国第一个皇帝是谁？" },
              { "role": "assistant", "content": "秦始皇" },
              { "role": "user", "content": "秦始皇修的长城吗" },
              { "role": "assistant", "content": "是的" },
              { "role": "user", "content": queryPrompt }
            ]
          }
        }
      };

      this.ttsWS.send(JSON.stringify(params));
    },

    handleResult(resultData, questionType) {
      try {
        const jsonData = JSON.parse(resultData);

        if (jsonData.payload && jsonData.payload.choices && jsonData.payload.choices.text) {
          const content = jsonData.payload.choices.text[0].content;
          this.totalRes += content;

          if (jsonData.header.status === 2) {
            this.processCompleteResult(this.totalRes, questionType);
          }
        }

        if (jsonData.header.code !== 0) {
          alert(`分析失败: ${jsonData.header.code}:${jsonData.header.message}`);
          console.error(`${jsonData.header.code}:${jsonData.header.message}`);
          this.setStatus(questionType, 'error');
          return;
        }
      } catch (error) {
        console.error('解析返回结果失败:', error);
        this.setStatus(questionType, 'error');
      }
    },

    processCompleteResult(content, questionType) {
      let formattedContent = this.formatResult(content);

      if (questionType === 'advantage') {
        this.advantageText = content;
        this.formattedAdvantageText = formattedContent;
      } else {
        this.disadvantageText = content;
        this.formattedDisadvantageText = formattedContent;
      }
    },

    formatResult(content) {
      // 先处理**包裹的内容，将其转换为<strong>标签
      const withBold = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

      // 处理换行
      const withLineBreaks = withBold.replace(/\n/g, '<br>');

      // 智能识别列表格式并包装（保留原有列表结构）
      if (withLineBreaks.match(/<strong>/) && (withLineBreaks.match(/\d+\.\s/) || withLineBreaks.match(/\d+\)\s/))) {
        // 将列表项包装为ol/li
        return withLineBreaks.replace(/(^|<br>)(\d+[.\)]\s+<strong>.*?<\/strong>)/g, '$1<li>$2</li>');
      }

      return withLineBreaks;
    },

    setStatus(questionType, status) {
      if (questionType === 'advantage') {
        this.advantageStatus = status;
      } else {
        this.disadvantageStatus = status;
      }
    },

    analyzeAdvantages() {
      if (this.inputText.trim() === '') {
        alert('请先输入面试回答内容');
        return;
      }

      if (['init', 'error'].includes(this.advantageStatus)) {
        this.advantageText = '';
        this.formattedAdvantageText = '';
        this.totalRes = '';
        this.connectWebSocket('advantage');
      }
    },

    analyzeDisadvantages() {
      if (this.inputText.trim() === '') {
        alert('请先输入面试回答内容');
        return;
      }

      if (['init', 'error'].includes(this.disadvantageStatus)) {
        this.disadvantageText = '';
        this.formattedDisadvantageText = '';
        this.totalRes = '';
        this.connectWebSocket('disadvantage');
      }
    }
  },
  beforeDestroy() {
    if (this.ttsWS && this.ttsWS.readyState !== WebSocket.CLOSED) {
      this.ttsWS.close();
    }
  }
};
</script>

<style scoped>
.page-main {
  text-align: center;
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  font-size: 14px;
  resize: vertical;
  box-sizing: border-box;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin: 15px 0;
}

button {
  padding: 10px 20px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  min-width: 120px;
}

.audio-ctrl-btn.loading {
  background-color: #2563eb;
  cursor: not-allowed;
}

.audio-ctrl-btn.error {
  background-color: #ef4444;
}

h3 {
  text-align: left;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.result-container {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
  min-height: 200px;
  text-align: left;
  white-space: pre-wrap;
  overflow-y: auto;
  max-height: 300px;
}

.advantage {
  color: #10b981;
  border-color: #d1fae5;
}

.disadvantage {
  color: #ef4444;
  border-color: #fee2e2;
}

.advantage strong, .disadvantage strong {
  font-weight: bold;
}

ol {
  padding-left: 20px;
  margin-top: 10px;
}

li {
  margin-bottom: 8px;
}
</style>
